package com.pe.server;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pe.controller.IService;
import com.pe.service.param.IServiceParam;
import com.pe.service.response.IServiceResponse;
import com.pe.utils.GsonUtil;

public class ServiceHandler extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4266522342776322088L;
	@SuppressWarnings("unchecked")
	private Map<String, IService> serviceInstances = new HashMap<String, IService>();
	private Map<String, IServiceParam> serviceParamInstances = new HashMap<String, IServiceParam>();
	@SuppressWarnings("unchecked")
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		Enumeration<String> services= config.getInitParameterNames();
		while(services.hasMoreElements()){
			try {
				String serviceName=services.nextElement();
				Object obj=Class.forName(config.getInitParameter(serviceName)).newInstance();
				if(serviceName.contains("param")){
					IServiceParam serviceParam = (IServiceParam)obj;
					serviceParamInstances.put(serviceName, serviceParam);
				}else{
					IService service=(IService)obj;
					serviceInstances.put(serviceName, service);	
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException{
		 doPost(req, resp);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws IOException {
		Map<String, String[]> reqParams= req.getParameterMap();
		String serviceCalled = req.getPathInfo().substring(1);
		IServiceParam serviceParam= serviceParamInstances.get(serviceCalled+".param");
		serviceParam.parseServiceParam(reqParams);
		IServiceResponse<IServiceParam> serviceResponse = serviceInstances.get(serviceCalled).handleService(serviceParam);
		String response= GsonUtil.serializeObjectToJson(serviceResponse);
		doRedirect(response, res);
		OutputStream os= res.getOutputStream();
		os.write(response.getBytes());
		os.flush();
		os.close();
	}
	
	@SuppressWarnings("unchecked")
	private void doRedirect(String response,HttpServletResponse httpRes) throws IOException{
		Map responseAttrs=GsonUtil.fromJson(response);
		Object serviceName = responseAttrs.get("serviceName");
		Object status = responseAttrs.get("status");
		//TODO Need Error message implementation
		if((serviceName.equals("login") ||serviceName.equals("register"))&& status.equals("ok")){
			httpRes.sendRedirect("/html/compose.html");
			return;
		}else if(serviceName.equals("login")){
			httpRes.sendRedirect("/html/error/error.html");
			return;
		}
	}

}
